<template>
  <div>
    <el-row :gutter="20" style="margin-bottom:100px" v-if="classData.length>0">
      <el-col
        :xs="6"
        :sm="6"
        :md="6"
        :lg="6"
        :xl="6"
        v-for="(item,index) in classData"
        :key="index"
        class="cols"
      >
        <el-card style="position:relative">
          <span class="score">{{item.score}}</span>
          <img :src="item.imgSrc" alt class="image" @click="navTo(item)">
          <div>
            <el-tooltip :content="item.label" placement="bottom-start" effect="light">
              <h3
                class="cols_label"
                style="margin:10px 0"
                @click="navTo(item)"
              >{{item.label|readmore(15,'....')}}</h3>
            </el-tooltip>
            <div>
              <span @click="navTo(item)">{{item.classNum}}节课</span>
              <el-tag
                size="small"
                :hit="hit"
                v-for="(tag,index) in item.tags"
                :key="index"
                style="margin:0px 5px;"
              >{{tag}}</el-tag>
              <div class="bottom">
                <div class="orange" @click="navTo(item)">￥{{item.price}}</div>
                <div>
                  <span
                    :class="item.liked==1?'iconfont iconCd':'iconfont icons'"
                    @click="like(item)"
                  >&#xe7c8;{{item.agree}}</span>
                  <span class="iconfont icons">&#xe675;{{item.message}}</span>
                  <span
                    @click="save(item)"
                    :class="item.collected==1?'iconfont iconCd':'iconfont icons'"
                  >&#xe7e0;{{item.save}}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col v-show="!recommend">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[8, 16, 32, 64, 128]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-bottom:100px" v-else>
      <h1 style="text-align:center">暂无检索结果，换个关键词检索试试吧</h1>
      <div style="text-align:center">
        <img src="../../assets/缺省.png" alt>
      </div>
    </el-row>
  </div>
</template>

<script>
import { getCourse, getCourseReco, saveCollect } from "@/api/ajax";
import axios from "axios";
export default {
  name: "Cards",
  props: ["search", "grade", "bread", "recommend", "vagesearch"],
  data() {
    return {
      hit: true,
      classData: [],
      currentPage: 1,
      total: 1,
      pagesize: 8
    };
  },
  components: {},
  methods: {
    handleSizeChange(val) {
      this.pagesize = val;
      this.addData(this.currentPage, val);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.addData(val, this.pagesize);
    },
    addData(currentPage, pagesize) {
      this.classData = [];
      let params = {};
      if (this.grade) {
        if (this.grade.comScore && this.grade.commentNum) {
          this.grade.commentNum = "";
        }
        if (this.grade.comScore) {
          params.sortfield = "comScore";
          params.comScore = parseInt(this.grade.comScore);
        }
        if (this.grade.commentNum) {
          params.sortfield = "commentNum";
          params.commentNum = parseInt(this.grade.commentNum);
        }
      }

      if (this.search) {
        params.category = this.search;
      } else if (this.vagesearch) {
        params.title = this.vagesearch;
      }
      if (currentPage) {
        params.page = currentPage;
      } else {
        params.page = this.currentPage;
      }

      if (pagesize) {
        params.pagesize = pagesize;
      } else {
        params.pagesize = this.pagesize;
      }

      if (this.recommend) {
        getCourseReco().then(res => {
          _(res.data.data).forEach((v, i, arr) => {
            this.classData.push({
              imgSrc: v.cover,
              label: v.title,
              liked: v.liked,
              collected: v.collected,
              price: v.officialPrice,
              price: v.officialPrice,
              message: v.commentNum,
              score: v.comScore,
              save: v.collection,
              agree: v.userLike,
              id: v.id
            });
          });
        });
      } else {
        setTimeout(() => {
          getCourse(params).then(res => {
            this.total = res.data.data.total;
            _(res.data.data.rows).forEach((v, i, arr) => {
              this.classData.push({
                imgSrc: v.cover,
                label: v.title,
                liked: v.liked,
                collected: v.collected,
                price: v.officialPrice,
                price: v.officialPrice,
                message: v.commentNum,
                score: v.comScore,
                save: v.collection,
                agree: v.userLike,
                id: v.id
              });
            });
          });
        }, 200);
      }
    },
    navTo(item) {
      if (this.bread) {
        this.$router.push({
          name: "classDetail",
          query: {
            item: JSON.stringify(item),
            id: item.id,
            breads: JSON.stringify(this.bread)
          }
        });
      } else {
        let bread = [
          {
            path: "/",
            name: "首页"
          }
        ];
        this.$router.push({
          name: "classDetail",
          query: {
            item: JSON.stringify(item),
            id: item.id,
            breads: JSON.stringify(bread)
          }
        });
      }
    },
    save(item) {
      let params = {};
      params.action = item.collected == 1 ? 0 : 1;
      if (!localStorage.getItem("token")) {
        this.$message.error("请登录");
        this.$bus.$emit("loginModal");
      } else {
        axios({
          method: "post",
          url: `account/a/h/course/${item.id}/api/collection/?action=${
            params.action
          }`,
          headers: {
            "Content-type": "application/json",
            token: localStorage.getItem("token")
          }
        }).then(res => {
          if (res.data.code == 0) {
            let msg = item.collected == 1 ? "取消成功" : "收藏成功";
            this.$message({
              showClose: true,
              message: msg,
              duration: 2000,
              type: "success"
            });
            item.collected = res.data.data.action;
          } else {
            this.$message({
              showClose: true,
              message: "抱歉，收藏失败",
              duration: 2000,
              type: "error"
            });
          }
        });
      }
    },
    like(item) {
      let params = {};
      params.action = item.liked == 1 ? 0 : 1;
      if (!localStorage.getItem("token")) {
        this.$message.error("请登录");
        this.$bus.$emit("loginModal");
      } else {
        axios({
          method: "post",
          url: `account/a/h/course/${item.id}/api/like/?action=${
            params.action
          }`,
          data: {},
          headers: {
            "Content-type": "application/json",
            token: localStorage.getItem("token")
          }
        }).then(res => {
          if (res.data.code == 0) {
            let msg = item.liked == 1 ? "取消成功" : "点赞成功";
            this.$message({
              showClose: true,
              message: msg,
              duration: 2000,
              type: "success"
            });
            item.liked = res.data.data.action;
            console.log(item);
            
          } else {
            this.$message({
              showClose: true,
              message: "抱歉，点赞失败",
              duration: 2000,
              type: "error"
            });
          }
        });
      }
    }
  },
  watch: {
    search: function(val) {
      this.addData();
    },
    vagesearch: function(val) {
      this.addData();
    }
  },
  mounted() {
    this.addData();
  }
};
</script>

<style lang="less" scoped>
@import "~styles/z.less";
@import "~styles/css3.less";
@import "~styles/variables.less";
.cols {
  margin: 20px 0;
  cursor: pointer;
  .cols_label {
    .secondFont;
    margin: 5px 0px;
  }
  .image {
    width: 100%;
    height: 140px;
  }
  .score {
    .abs;
    .dib;
    color: white;
    background: orange;
    width: 60px;
    text-align: center;
    line-height: 30px;
    font-size: 20px;
    right: 20px;
    height: 30px;
  }
  .bottom {
    margin-bottom: -10px;
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    .orange {
      color: orange;
      font-size: 18px;
    }
    .icons {
      font-size: 14px;
      color: #606266;
      cursor: pointer;
      margin: 0 2px;
    }
    .iconCd {
      font-size: 14px;
      color: orange;
      cursor: pointer;
      margin: 0 2px;
    }
  }
}
</style>
